import os
from datetime import timedelta
from flask import Flask, render_template, request, redirect, url_for, session, flash
from functools import wraps

app = Flask(__name__)
# 使用更安全的密钥
app.secret_key = os.urandom(24)
# 添加安全配置
app.config.update(
    SESSION_COOKIE_SECURE=False,  # 如果没有 HTTPS，设置为 False
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE='Lax',
    PERMANENT_SESSION_LIFETIME=timedelta(minutes=30)
)

# 登录验证装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'logged_in' not in session:
            flash('请先登录', 'error')
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 模拟用户数据
users = {
    'admin': 'password123'
}

@app.route('/')
def index():
    return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username in users and users[username] == password:
            session['logged_in'] = True
            session['username'] = username
            flash('登录成功！', 'success')
            return redirect(url_for('dashboard'))
        else:
            flash('用户名或密码错误', 'error')
    
    return render_template('login.html')

@app.route('/dashboard')
@login_required
def dashboard():
    username = session.get('username')
    stats = {
        'total_tasks': 10,
        'completed_tasks': 5,
        'pending_tasks': 5
    }
    recent_activities = [
        {'action': '完成了任务', 'time': '2024-03-20 10:30'},
        {'action': '创建了新项目', 'time': '2024-03-20 09:15'},
        {'action': '更新了设置', 'time': '2024-03-19 16:45'}
    ]
    return render_template('dashboard.html', username=username, stats=stats, activities=recent_activities)

@app.route('/logout')
def logout():
    session.clear()
    flash('已成功退出登录', 'info')
    return redirect(url_for('login'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True) 